package com.cchr.acms.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cchr.acms.constant.CaseStatus;
import com.cchr.acms.model.AbuseType;
import com.cchr.acms.model.AbusedPerson;
import com.cchr.acms.model.Action;
import com.cchr.acms.model.AjaxResult;
import com.cchr.acms.model.Attorney;
import com.cchr.acms.model.CaseAudit;
import com.cchr.acms.model.CaseFollowUp;
import com.cchr.acms.model.CaseInfo;
import com.cchr.acms.model.CaseInfoQueryEntity;
import com.cchr.acms.model.CaseInfoResult;
import com.cchr.acms.model.DoctorInfo;
import com.cchr.acms.model.Drug;
import com.cchr.acms.model.FacilityInfo;
import com.cchr.acms.model.ReportingPerson;
import com.cchr.acms.service.AbuseTypeService;
import com.cchr.acms.service.AbusedPersonService;
import com.cchr.acms.service.ActionService;
import com.cchr.acms.service.AttorneyService;
import com.cchr.acms.service.CaseAuditService;
import com.cchr.acms.service.CaseFollowUpService;
import com.cchr.acms.service.CaseInfoService;
import com.cchr.acms.service.DoctorInfoService;
import com.cchr.acms.service.DrugService;
import com.cchr.acms.service.FacilityInfoService;
import com.cchr.acms.service.ReportingPersonService;
import com.cchr.acms.util.ChangeHistoryDisplayData;
import com.cchr.acms.util.ChangeResult;
import com.cchr.acms.util.DataTableVO;
import com.cchr.acms.util.DataUtil;
import com.cchr.acms.util.HtmlComponentUtil.SelectOption;
import com.cchr.acms.util.ListUtil;
import com.cchr.acms.util.PageableDataVO;

@Controller
@RequestMapping("/case")
public class CaseInfoController {
	@Autowired
	private CaseInfoService caseInfoService;
	@Autowired
	private AbusedPersonService abusedPersonService;
	@Autowired
	private ReportingPersonService reportingPersonService;
	@Autowired
	private DrugService drugService;
	@Autowired
	private AbuseTypeService abuseTypeService;
	@Autowired
	private FacilityInfoService FacilityInfoService;
	@Autowired
	private DoctorInfoService doctorInfoService;
	@Autowired
	private AttorneyService attorneyService;
	@Autowired
	private ActionService actionService;
	@Autowired
	private CaseFollowUpService caseFollowUpService;
	@Autowired
	private CaseAuditService caseAuditService;
	
	public static String[] COUNTRY = {"Afghanistan","Albania","Algeria","American Samoa","Andorra","Angola","Antigua and Barbuda","Argentina","Armenia","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Brazil","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central African Republic","Chad","Chile","China","Colombia","Comoros","Congo, Democratic Republic of the","Congo, Republic of the","Costa Rica","Côte d'Ivoire","Croatia","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","East Timor","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Faroe Islands","Fiji","Finland","France","French Polynesia","Gabon","Gambia","Georgia","Germany","Ghana","Greece","Greenland","Grenada","Guam","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","North Korea","South Korea","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","New Zealand","Nicaragua","Niger","Nigeria","Northern Mariana Islands","Norway","Oman","Pakistan","Palau","Palestine, State of","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Romania","Russia","Rwanda","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Sint Maarten","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","Spain","Sri Lanka","Sudan","Sudan, South","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Togo","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Virgin Islands, British","Virgin Islands, U.S.","Yemen","Zambia","Zimbabwe"};
	public static String[] DOCTYPE = {"Psychiatrist","Psychologist","General Practitioner","Neurologist", "Pediatrician", "Other"};
	public static String[] RELATION = {"Mother","Father","Sister","Brother","Grandparent","Aunt","Uncle","Friend","Other"};
	public static String[] FACILITY_TYPE = {"In-Patient Psychiatric Hospital","Out-Patient Psychiatric Hospital","Private Doctor's Office","Clinic","General Hospital","Nursing Home","School","Other"};
	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	public static String[] CONTATC_WAY = {"Phone","Email","Letter","In person"};
	public static String[] INSURANCE_TYPE={"Private Insurance","Medicare","Medicaid","Other"};
	public static String[] ATTORNEY_STATUS={"Has attorney","Wants attorney","No interest in attorney"};
	private String flagNew;
	private String flagOld;
	private String byWhoOld;
	private String byWhoNew;
	private String acceptFlagOld;
	private String acceptFlagNew;
	
	@RequestMapping(value={"/create"}, method = RequestMethod.GET)
	public String createPage(HttpServletRequest request){
    	List<Drug> drugs = drugService.getAllDrug();
    	
    	List<SelectOption> datas = new ArrayList<SelectOption>();
    	for(Drug drug : drugs)
    	{
    		SelectOption op = new SelectOption();
    		op.setGroup(drug.getType());
    		op.setLabel(drug.getName());
    		op.setValue(String.valueOf(drug.getId()));
    		datas.add(op);
    	}
    	request.setAttribute("datas", datas);
    	
    	List<SelectOption> countryDatas = new ArrayList<SelectOption>();
    	for (int i = 0; i < COUNTRY.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(COUNTRY[i]);
    		op.setValue(COUNTRY[i]);
    		countryDatas.add(op);
		}
    	request.setAttribute("countryDatas", countryDatas);
    	
    	List<AbuseType> abuseTypes = abuseTypeService.getAllAbuseType();
    	request.setAttribute("abuseTypes", abuseTypes);
    	
    	List<Action> actions = actionService.getAllAction();
    	request.setAttribute("actions", actions);
    	
    	List<SelectOption> docTypes = new ArrayList<SelectOption>();
    	for (int i = 0; i < DOCTYPE.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(DOCTYPE[i]);
    		op.setValue(DOCTYPE[i]);
    		docTypes.add(op);
		}
    	request.setAttribute("docTypes", docTypes);
    	
    	List<SelectOption> relations = new ArrayList<SelectOption>();
    	for (int i = 0; i < RELATION.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(RELATION[i]);
    		op.setValue(RELATION[i]);
    		relations.add(op);
		}
    	request.setAttribute("relations", relations);
    	
    	List<SelectOption> facilityTypes = new ArrayList<SelectOption>();
    	for (int i = 0; i < FACILITY_TYPE.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(FACILITY_TYPE[i]);
    		op.setValue(FACILITY_TYPE[i]);
    		facilityTypes.add(op);
		}
    	request.setAttribute("facilityTypes", facilityTypes);
        return "case/create";
	}
	
	@RequestMapping(value={"/create"}, method = RequestMethod.POST)
	public String addCase(CaseInfo caseInfo,String[] drugIds,String[] actionsCheckbox,String[] abusetypeCheckbox,HttpSession session) throws ParseException{
		String currUser = "";
		Date now = new Date();
		caseInfo.setStatus(CaseStatus.NEW.getValue());
		caseInfo.setCreatedBy(currUser);
		caseInfo.setLastUpdateDate(now);
		caseInfo.setLastUpdatedBy(currUser);
		caseInfo.setCreateDate(now);
		
		caseInfo.setTypeIds(ListUtil.ArrayToString(abusetypeCheckbox, ","));
		caseInfo.setDrugIds(ListUtil.ArrayToString(drugIds, ","));
		caseInfo.setActionIds(ListUtil.ArrayToString(actionsCheckbox, ","));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
		String caseNo = "C" + sdf.format(new Date());
		caseInfo.setCaseNo(caseNo);
		caseInfoService.insertCaseInfo(caseInfo);
		int caseId = caseInfo.getId();
		//先生成caseid
		AbusedPerson abusedPerson = caseInfo.getAbusedPerson();
		abusedPerson.setCaseId(caseId);
		abusedPersonService.insertAbusedPerson(abusedPerson);
		ReportingPerson reportingPerson = caseInfo.getReportedBy();
		reportingPerson.setCaseId(caseId);
		reportingPersonService.insertReportingPerson(reportingPerson);
	 
		int fsize=0; 
		if(caseInfo.getFacilityInfos()!=null&&(fsize = caseInfo.getFacilityInfos().size())>0){
			for (int i = 0; i < fsize; i++) {
				FacilityInfo info = caseInfo.getFacilityInfos().get(i);
				info.setCaseId(caseId);
				FacilityInfoService.insertFacilityInfo(info);
			}
		}
		int dsize = 0;
		if(caseInfo.getDoctorInfos()!=null&&(dsize = caseInfo.getDoctorInfos().size())>0){
			for (int i = 0; i < dsize; i++) {
				DoctorInfo info = caseInfo.getDoctorInfos().get(i);
				info.setCaseId(caseId);
				doctorInfoService.insertDoctorInfo(info);
			}
			
		}

		Attorney attorney = caseInfo.getAttorney();
		attorney.setCaseId(caseId);
		attorneyService.insertAttorney(attorney);
		return "redirect:create/success/" + caseInfo.getId();
	}
	
	@RequestMapping(value={"/create/success/{id}"}, method = RequestMethod.GET)
	public String createSuccessPage(@PathVariable Integer id) throws ParseException{
		return "/case/create_success";
	}
	
	@RequestMapping(value={"/create/success/{id}"}, method = RequestMethod.POST)
	public String createSuccess(String emailAddress, @PathVariable Integer id) throws ParseException{
		CaseInfo caseInfo = caseInfoService.getCaseInfoById(id);
		caseInfo.setSubEmail(emailAddress);
		caseInfoService.updateCaseInfo(caseInfo);
		return "redirect:http://www.cchrint.org/thank-you-for-reporting/";
	}
	
	@RequestMapping(value={"/showAbuseList"})
	public String showAbuseList(HttpServletRequest request){
    	List<SelectOption> countryDatas = new ArrayList<SelectOption>();
    	for (int i = 0; i < COUNTRY.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(COUNTRY[i]);
    		op.setValue(COUNTRY[i]);
    		countryDatas.add(op);
		}
    	request.setAttribute("countryDatas", countryDatas);
    	
    	List<SelectOption> facilityTypes = new ArrayList<SelectOption>();
    	for (int i = 0; i < FACILITY_TYPE.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(FACILITY_TYPE[i]);
    		op.setValue(FACILITY_TYPE[i]);
    		facilityTypes.add(op);
		}
    	request.setAttribute("facilityTypes", facilityTypes);
    	
    	List<SelectOption> docTypes = new ArrayList<SelectOption>();
    	for (int i = 0; i < DOCTYPE.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(DOCTYPE[i]);
    		op.setValue(DOCTYPE[i]);
    		docTypes.add(op);
		}
    	request.setAttribute("docTypes", docTypes);
    	
    	List<Drug> drugs = drugService.getAllDrug();
    	List<SelectOption> datas = new ArrayList<SelectOption>();
    	List<String> drugTypes = new ArrayList<String>();
    	List<SelectOption> drugTypeOptions = new ArrayList<SelectOption>();
    	for(Drug drug : drugs)
    	{
    		SelectOption op = new SelectOption();
    		op.setGroup(drug.getType());
    		op.setLabel(drug.getName());
    		op.setValue(String.valueOf(drug.getId()));
    		datas.add(op);
    		if(!drugTypes.contains(drug.getType())){
    			drugTypes.add(drug.getType());
    		}
    	}
    	request.setAttribute("drugs", datas);
    	
    	for(String dn : drugTypes)
    	{
    		SelectOption op = new SelectOption();
    		op.setLabel(dn);
    		op.setValue(dn);
    		drugTypeOptions.add(op);
    	}
    	request.setAttribute("drugTypeOptions", drugTypeOptions);
    	
    	List<SelectOption> abuseTypes = new ArrayList<SelectOption>();
    	List<AbuseType> abuseList = abuseTypeService.getAllAbuseType();
    	for (AbuseType abuseType : abuseList) {
    		SelectOption op = new SelectOption();
    		op.setLabel(abuseType.getName());
    		op.setValue(abuseType.getId()+"");
    		abuseTypes.add(op);
		}
    	request.setAttribute("abuseTypes", abuseTypes);
    	
    	List<SelectOption> insTypes = new ArrayList<SelectOption>();
    	for (int i = 0; i < INSURANCE_TYPE.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(INSURANCE_TYPE[i]);
    		op.setValue(INSURANCE_TYPE[i]);
    		insTypes.add(op);
		}
    	request.setAttribute("insTypes", insTypes);
    	
    	return "case/showCase";
	}
	
	@RequestMapping(value={"/showAbuseListJson"}, method = RequestMethod.POST)
    @ResponseBody
    public PageableDataVO<CaseInfoResult> getAbuseList(DataTableVO dataTableVO, CaseInfoQueryEntity queryEntity) {
		//解析
		int index = dataTableVO.getStart();
		int offset = dataTableVO.getLength();
		PageableDataVO<CaseInfoResult> data = new PageableDataVO<CaseInfoResult>();
		List<CaseInfoResult> result = new ArrayList<CaseInfoResult>();
        try {
        	List<CaseInfo> list = caseInfoService.queryAbuseInfo(queryEntity,index,offset);
        	int total = caseInfoService.queryTotal(queryEntity);
        	data.setiTotalDisplayRecords(total);
    		data.setiTotalRecords(total);
        	for (int i = 0; i < list.size(); i++) {
        		list.get(i).setStatus(CaseStatus.getKeyByValue(list.get(i).getStatus()));
        		AbusedPerson abusedPerson = abusedPersonService.getAbusedPersonByCaseId(list.get(i).getId());
        		list.get(i).setAbusedPerson(abusedPerson);
        		List<DoctorInfo> doctorInfos = doctorInfoService.queryDoctorInfoByCaseId(list.get(i).getId());
        		list.get(i).setDoctorInfos(doctorInfos);
        		List<FacilityInfo> facilityInfos = FacilityInfoService.getFacilityInfoByCaseId(list.get(i).getId());
        		list.get(i).setFacilityInfos(facilityInfos);
        		CaseInfoResult rs = new CaseInfoResult();
        		// mock data
        		rs.setSequence(list.get(i).getCaseNo());
        		rs.setProcessedBy("CCHR INT");
        		// mock end
        		rs.setId(list.get(i).getId());
        		//patient name
        		rs.setPatientName(list.get(i).getAbusedPerson().getFirstName() + " " + list.get(i).getAbusedPerson().getLastName());
        		//create time
        		rs.setCreateTime(list.get(i).getCreateDate());
        		//status
        		rs.setStatus(list.get(i).getStatus().toUpperCase());
        		rs.setCity(list.get(i).getAbusedPerson().getCity());
        		rs.setLastUpdateDate(list.get(i).getLastUpdateDate());
        		rs.setLastUpdatedBy(list.get(i).getLastUpdatedBy());
        		//doctor name
        		List<DoctorInfo> dlist = list.get(i).getDoctorInfos();
        		StringBuilder sb = new StringBuilder();
        		if(dlist!=null&&(dlist.size()>0)){
        			for (int j = 0; j < dlist.size(); j++) {
        				String  docNameString = StringUtils.trimToEmpty(dlist.get(j).getName());
        				if(StringUtils.isNotBlank(docNameString))
        				{
        					docNameString += " ";
        				}
        				docNameString += StringUtils.trimToEmpty(dlist.get(j).getLastName());
						if(StringUtils.isNotBlank(docNameString))
						{
							if(sb.length() > 0)
							{
								sb.append(",");
							}
							sb.append(docNameString);
						}
					}
        		}
        		rs.setDoctorName(sb.toString());
        		
        		//facility name
        		List<FacilityInfo> flist = list.get(i).getFacilityInfos();
        		sb = new StringBuilder();
        		if(flist!=null && flist.size()>0){
        			for (int j = 0; j < flist.size(); j++) {
        				if(StringUtils.isNotBlank(flist.get(j).getName()))
						{
        					if(sb.length() > 0)
							{
								sb.append(",");
							}
							sb.append(flist.get(j).getName());;
						}
					}
        		}
        		rs.setFacilityName(sb.toString());
        	
        		result.add(rs);
			}
        	data.addData(result);
            return data;

        } catch (Exception e) {
        	e.printStackTrace();
            return data;
        }
    }

	
	@RequestMapping(value={"/detail/{id}"}, method = RequestMethod.GET)
	public String detailPage(HttpServletRequest request, @PathVariable Integer id, String edit)
	{
		request.setAttribute("edit", edit);
		if(id != null)
		{
			CaseInfo caseInfo = caseInfoService.getCaseInfoById(id);
			request.setAttribute("caseStatus", CaseStatus.getList());
			if(caseInfo != null)
			{
				AbusedPerson abusedPerson = abusedPersonService.getAbusedPersonByCaseId(id);
				caseInfo.setAbusedPerson(abusedPerson);
				ReportingPerson reportingPerson = reportingPersonService.getReportingPersonByCaseId(id);
				caseInfo.setReportedBy(reportingPerson);
				Attorney attorney = attorneyService.getAttorneyByCaseId(id);
				caseInfo.setAttorney(attorney);
				List<DoctorInfo> doctorInfos = doctorInfoService.queryDoctorInfoByCaseId(id);
				caseInfo.setDoctorInfos(doctorInfos);
				List<FacilityInfo> facilityInfos = FacilityInfoService.getFacilityInfoByCaseId(id);
				caseInfo.setFacilityInfos(facilityInfos);
				
				String typeIds = caseInfo.getTypeIds();
				if(typeIds != null)
				{
					StringBuilder sb = new StringBuilder();
					String[] typeIdArr = typeIds.split(",");
					if(typeIdArr.length > 0)
					{
						List<String> typeIdList = Arrays.asList(typeIdArr);
						List<AbuseType> abuseTypes = abuseTypeService.getAllAbuseType();
				    	for(AbuseType type : abuseTypes)
				    	{
				    		if(typeIdList.contains(String.valueOf(type.getId())))
				    		{
				    			sb.append(type.getName()).append(", ");
				    		}
				    	}
					}
					if(sb.lastIndexOf(",") == sb.length() - 2)
					{
						sb.delete(sb.length() - 2, sb.length());
					}
					request.setAttribute("typeIds", sb.toString());
				}
				
				String drugIds = caseInfo.getDrugIds();
				if(drugIds != null)
				{
					String[] drugIdArr = drugIds.split(",");
					if(drugIdArr.length > 0)
					{
						List<String> drugIdList = Arrays.asList(drugIdArr);
						List<Drug> drugs = drugService.getAllDrug();
						List<String> drugNames = new ArrayList<String>();
				    	for(Drug drug : drugs)
				    	{
				    		if(drugIdList.contains(String.valueOf(drug.getId())))
				    		{
				    			drugNames.add(drug.getName());
				    		}
				    	}
				    	request.setAttribute("drugNames", drugNames);
					}
				}
				
				String actionIds = caseInfo.getActionIds();
				if(actionIds != null)
				{
					String[] actionIdArr = actionIds.split(",");
					if(actionIdArr.length > 0)
					{
						List<String> actionIdList = Arrays.asList(actionIdArr);
						List<Action> actions = actionService.getAllAction();
						List<String> acs = new ArrayList<String>();
				    	for(Action action : actions)
				    	{
				    		if(actionIdList.contains(String.valueOf(action.getId())))
				    		{
				    			acs.add(action.getName());
				    		}
				    	}
				    	request.setAttribute("actions", acs);
					}
				}
				request.setAttribute("caseInfo", caseInfo);
			}
			// audit list
			List<CaseAudit> caseAudits = caseAuditService.getAllCaseAuditByCaseId(caseInfo.getId());
			request.setAttribute("caseAudits", caseAudits);
			CaseFollowUp followup = caseFollowUpService.getCaseFollowUpByCaseId(id);

			if(followup == null)
			{
				followup = new CaseFollowUp();
			}
			request.setAttribute("contactWays", CONTATC_WAY);
			request.setAttribute("insuranceType", INSURANCE_TYPE);
			request.setAttribute("attorneyStatus", ATTORNEY_STATUS);
			request.setAttribute("followup", followup);
			
			// 根据类型设置不同的Staff Memeber Name
			if(followup != null)
			{
				if("0".equals(followup.getFollowedType()))
				{
					followup.setStaffMemeberFirstName1(followup.getStaffMemeberFirstName());
					followup.setStaffMemeberLastName1(followup.getStaffMemeberLastName());
				}
				else
				{
					followup.setStaffMemeberFirstName2(followup.getStaffMemeberFirstName());
					followup.setStaffMemeberLastName2(followup.getStaffMemeberLastName());
				}
			}
			
	    	List<SelectOption> countryDatas = new ArrayList<SelectOption>();
	    	for (int i = 0; i < COUNTRY.length; i++) {
	    		SelectOption op = new SelectOption();
	    		op.setLabel(COUNTRY[i]);
	    		op.setValue(COUNTRY[i]);
	    		countryDatas.add(op);
			}
	    	List<SelectOption> caseCategory = new ArrayList<SelectOption>();
	    	for(int i=1; i<6; i++)
	    	{
	    		SelectOption op = new SelectOption();
	    		op.setLabel(i + "");
	    		op.setValue(i + "");
	    		caseCategory.add(op);
	    	}
	    	request.setAttribute("caseCategory", caseCategory);
	    	request.setAttribute("countryDatas", countryDatas);
	    	if(edit == null || StringUtils.isEmpty(edit))
	    	{
	    		return "case/detail/followup";
	    	}
	    	else
	    	{
	    		return "case/detail/editfollowup";
	    	}
		}
    	
		return "case/detail/followup";
	}
	
	@RequestMapping(value={"/detail/{id}"}, method = RequestMethod.POST)
	public String addDetail(HttpServletRequest request, CaseFollowUp caseFollowUp, @PathVariable Integer id, String caseStatus,
			String[] contactWaysCheckbox, String[] insuranceTypeCheckbox, String[] attorneyStatusCheckbox){
		ChangeHistoryDisplayData displayData= new ChangeHistoryDisplayData();
		
		String currUser = (String)request.getSession().getAttribute("userName");
		//status:new processing,completed
		if(attorneyStatusCheckbox!=null && insuranceTypeCheckbox.length>0){
			StringBuilder attorneyStatus = new StringBuilder();
			for (String status : attorneyStatusCheckbox) {
				attorneyStatus.append(status).append(",");
			}
			caseFollowUp.setAttorneyStatus(attorneyStatus.toString());
		}
		
		if(insuranceTypeCheckbox!=null && insuranceTypeCheckbox.length>0){
			StringBuilder insuranceType = new StringBuilder();
			for (String type : insuranceTypeCheckbox) {
				insuranceType.append(type).append(",");
			}
			caseFollowUp.setInsuranceType(insuranceType.toString());
		}
		
		if(contactWaysCheckbox!=null && contactWaysCheckbox.length>0){
			StringBuilder contactWays = new StringBuilder();
			for (String contact : contactWaysCheckbox) {
				contactWays.append(contact).append(",");
				
			}
			caseFollowUp.setContactedBy(contactWays.toString());
		}

		caseFollowUp.setCaseId(id);
		caseStatus = StringUtils.isEmpty(caseStatus) ? CaseStatus.COMPLETED.getValue() : caseStatus;
		if(caseStatus.equals(CaseStatus.NEW.getValue()))
		{
			caseStatus = CaseStatus.INPROCESS.getValue();
		}
		// 根据类型获取不同的Staff Memeber Name
		if("0".equals(caseFollowUp.getFollowedType()))
		{
			caseFollowUp.setStaffMemeberFirstName(caseFollowUp.getStaffMemeberFirstName1());
			caseFollowUp.setStaffMemeberLastName(caseFollowUp.getStaffMemeberLastName1());
		}
		else
		{
			caseFollowUp.setStaffMemeberFirstName(caseFollowUp.getStaffMemeberFirstName2());
			caseFollowUp.setStaffMemeberLastName(caseFollowUp.getStaffMemeberLastName2());
		}
		CaseInfo caseInfo = caseInfoService.getCaseInfoById(id);
		int result = 1;
		String statusAudit = "";
		if(!caseInfo.getStatus().equals(caseStatus))
		{
			result = caseInfoService.updateCaseStatus(id, caseStatus, request.getSession().getAttribute("userName").toString());
			
			statusAudit = "\"Follow Up\" section \"Case Status\" has changed from \"" + CaseStatus.getKeyByValue(caseStatus) + "\""+" to "+"\"" + CaseStatus.getKeyByValue(caseInfo.getStatus())+"\"";
		}
		CaseFollowUp followup = caseFollowUpService.getCaseFollowUpByCaseId(id);
		if(result > 0 && followup == null){
			caseFollowUpService.insertCaseFollowUp(caseFollowUp);
		}
		else if(result > 0 && followup != null)
		{
			try {
				// audit
				List<String> needComparedFields = new ArrayList<String>();
				needComparedFields.add("beenContacted");
				needComparedFields.add("contactedDate");
				needComparedFields.add("followedType");
				needComparedFields.add("chapter");
				needComparedFields.add("staffMemeberFirstName");
				needComparedFields.add("staffMemeberLastName");
				needComparedFields.add("contactedBy");
				needComparedFields.add("staffMemeberEmail");
				needComparedFields.add("staffMemeberPhoneNumber");
				needComparedFields.add("contactedNotes");  
				needComparedFields.add("userInsurance");
				needComparedFields.add("insuranceType");
				needComparedFields.add("insurance1CompanyName");
				needComparedFields.add("insurance2CompanyName");
				needComparedFields.add("notesOnInsuranceDetail");
				needComparedFields.add("attorneyStatus");
				needComparedFields.add("attorneyFirstName");
				needComparedFields.add("attorneyLastName");
				needComparedFields.add("notesOnAttorneyStatus");
				needComparedFields.add("referAttorneyStatus");
				needComparedFields.add("referAttorneyFirstName");
				needComparedFields.add("referAttorneyLastName");
				needComparedFields.add("referAttorneyDate");
				needComparedFields.add("referAttorneyAccteptDate");
				needComparedFields.add("referAttorneyAccteptFlag");
				needComparedFields.add("referAttorneyDeclinedFlag");
				needComparedFields.add("referAttorneyDeclinedDate");
				needComparedFields.add("referAttorneyDeclinedReason");
				needComparedFields.add("notesOnReferal");
				needComparedFields.add("filledWithAgency");
				needComparedFields.add("filleWithAgencyDate");
				needComparedFields.add("filledAgencyName");
				needComparedFields.add("filledAgencyContactName");
				needComparedFields.add("filledAgencyAddress");
				needComparedFields.add("filledAgencyCity");
				needComparedFields.add("filledAgencyState");
				needComparedFields.add("filledAgencyCountry");
				needComparedFields.add("filledAgencyZip");
				needComparedFields.add("compliantResponseReceived");
				needComparedFields.add("compliantResponseContent");
				needComparedFields.add("noteOnCompliant");
				needComparedFields.add("abusedPersonSigneWaiver");
				needComparedFields.add("abusedPersonSigneDate");
				needComparedFields.add("cchrReceivedAbusedDoc");
				needComparedFields.add("cchrReceivedAbusedDocDate");
				needComparedFields.add("otherActionsTaken");
				needComparedFields.add("currentStatusOnCase");
				needComparedFields.add("caseLastUpdatedDate");
				needComparedFields.add("caseCategory");
				List<ChangeResult> changeResults = DataUtil.compareObjectByFields(followup, caseFollowUp, needComparedFields);
				//System.out.println(changeResults.size());
				if(changeResults.size() > 0)
				{
					CaseAudit audit = new CaseAudit();
					audit.setAction("Update");
					audit.setUpdatedTime(new Date());
					audit.setUpdatedBy(currUser);
					audit.setCaseId(id);
					StringBuilder updateContent = new StringBuilder();
					for(ChangeResult changeResult : changeResults)
					{
						
						switch(changeResult.getKey()){
						case "beenContacted" :
						case "userInsurance" :
						case "referAttorneyStatus" :
						case "filledWithAgency" :
						case "compliantResponseReceived" :
						case "abusedPersonSigneWaiver" :
						case "cchrReceivedAbusedDoc" :
							if (changeResult.getOldValue().toString().equals("1"))
								{
								   flagOld = "yes";
								}else{
									flagOld = "no";
								}
							if (changeResult.getNewValue().toString().equals("1"))
							{
							   flagNew = "yes";
							}else{
								flagNew = "no";
							}
							
							updateContent.append("\"Follow Up\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  //LEON
							.append("\"").append(flagOld).append("\"").append(" to ").append("\"").append(flagNew).append("\"")
							.append("<br>");
							flagNew="";
							flagOld="";
							break;
						case "followedType" :
							if (changeResult.getOldValue().toString().equals("0")){
								byWhoOld = "CCHR International";
								
							}else{
								byWhoOld = "CCHR Chapter";}
							
							if (changeResult.getNewValue().toString().equals("0")){
								byWhoNew = "CCHR International";
							
							}else{
								byWhoNew = "CCHR Chapter";
							}
							updateContent.append("\"Follow Up\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  //LEON
							.append("\"").append(byWhoOld).append("\"").append(" to ").append("\"").append(byWhoNew).append("\"")
							.append("<br>");
							byWhoOld="";
							byWhoNew="";
							break;
						case "referAttorneyAccteptFlag":
						case "referAttorneyDeclinedFlag":
							if (null == changeResult.getOldValue()){
								acceptFlagOld = "no";
								
							}else{
								acceptFlagOld = "yes";}
							
							if (null == changeResult.getNewValue()){
								acceptFlagNew = "no";
							
							}else{
								acceptFlagNew = "yes";
							}
							updateContent.append("\"Follow Up\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  //LEON
							.append("\"").append(acceptFlagOld).append("\"").append(" to ").append("\"").append(acceptFlagNew).append("\"")
							.append("<br>");
							acceptFlagOld="";
							acceptFlagNew="";
							break;
							
						default: 
							
							updateContent.append("\"Follow Up\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  //LEON
							.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
							.append("<br>");

						}
						
					}
					updateContent.append(statusAudit);
					audit.setUpdatedAfter(updateContent.toString());
					caseAuditService.insertCaseAudit(audit);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			caseFollowUp.setId(followup.getId());
			BeanUtils.copyProperties(caseFollowUp, followup);
			caseFollowUpService.updateCaseFollowUp(followup);
		}
		
//		return "case/showCase";
		return "sys/autoClose";
	}
	
	@RequestMapping(value={"/edit/{id}"}, method = RequestMethod.GET)
	public String editPage(HttpServletRequest request, @PathVariable Integer id)
	{
		if(id != null)
		{
			CaseInfo caseInfo = caseInfoService.getCaseInfoById(id);
			request.setAttribute("caseStatus", CaseStatus.getList());
			// audit list
			List<CaseAudit> caseAudits = caseAuditService.getAllCaseAuditByCaseId(caseInfo.getId());
			request.setAttribute("caseAudits", caseAudits);
			if(caseInfo != null)
			{
				AbusedPerson abusedPerson = abusedPersonService.getAbusedPersonByCaseId(id);
				caseInfo.setAbusedPerson(abusedPerson);
				ReportingPerson reportingPerson = reportingPersonService.getReportingPersonByCaseId(id);
				caseInfo.setReportedBy(reportingPerson);
				Attorney attorney = attorneyService.getAttorneyByCaseId(id);
				caseInfo.setAttorney(attorney);
				List<DoctorInfo> doctorInfos = doctorInfoService.queryDoctorInfoByCaseId(id);
				caseInfo.setDoctorInfos(doctorInfos);
				List<FacilityInfo> facilityInfos = FacilityInfoService.getFacilityInfoByCaseId(id);
				caseInfo.setFacilityInfos(facilityInfos);
				
				String typeIds = caseInfo.getTypeIds();
				if(typeIds != null)
				{
					StringBuilder sb = new StringBuilder();
					String[] typeIdArr = typeIds.split(",");
					if(typeIdArr.length > 0)
					{
						List<String> typeIdList = Arrays.asList(typeIdArr);
						List<AbuseType> abuseTypes = abuseTypeService.getAllAbuseType();
				    	for(AbuseType type : abuseTypes)
				    	{
				    		if(typeIdList.contains(String.valueOf(type.getId())))
				    		{
				    			sb.append(type.getName()).append(", ");
				    		}
				    	}
					}
					if(sb.lastIndexOf(",") == sb.length() - 2)
					{
						sb.delete(sb.length() - 2, sb.length());
					}
					request.setAttribute("typeIds", sb.toString());
				}
				
				String drugIds = caseInfo.getDrugIds();
				if(drugIds != null)
				{
					String[] drugIdArr = drugIds.split(",");
					if(drugIdArr.length > 0)
					{
						List<String> drugIdList = Arrays.asList(drugIdArr);
						List<Drug> drugs = drugService.getAllDrug();
						List<String> drugNames = new ArrayList<String>();
				    	for(Drug drug : drugs)
				    	{
				    		if(drugIdList.contains(String.valueOf(drug.getId())))
				    		{
				    			drugNames.add(drug.getName());
				    		}
				    	}
				    	request.setAttribute("drugNames", drugNames);
					}
				}
				
				String actionIds = caseInfo.getActionIds();
				if(actionIds != null)
				{
					String[] actionIdArr = actionIds.split(",");
					if(actionIdArr.length > 0)
					{
						List<String> actionIdList = Arrays.asList(actionIdArr);
						List<Action> actions = actionService.getAllAction();
						List<String> acs = new ArrayList<String>();
				    	for(Action action : actions)
				    	{
				    		if(actionIdList.contains(String.valueOf(action.getId())))
				    		{
				    			acs.add(action.getName());
				    		}
				    	}
				    	request.setAttribute("myactions", acs);
					}
				}
				request.setAttribute("caseInfo", caseInfo);
			}
			CaseFollowUp followup = caseFollowUpService.getCaseFollowUpByCaseId(id);
			if(followup == null)
			{
				followup = new CaseFollowUp();
			}
			request.setAttribute("contactWays", CONTATC_WAY);
			request.setAttribute("insuranceType", INSURANCE_TYPE);
			request.setAttribute("attorneyStatus", ATTORNEY_STATUS);
			request.setAttribute("followup", followup);
			
			// 根据类型设置不同的Staff Memeber Name
			if(followup != null)
			{
				if("0".equals(followup.getFollowedType()))
				{
					followup.setStaffMemeberFirstName1(followup.getStaffMemeberFirstName());
					followup.setStaffMemeberLastName1(followup.getStaffMemeberLastName());
				}
				else
				{
					followup.setStaffMemeberFirstName2(followup.getStaffMemeberFirstName());
					followup.setStaffMemeberLastName2(followup.getStaffMemeberLastName());
				}
			}
			
	    	List<SelectOption> countryDatas = new ArrayList<SelectOption>();
	    	for (int i = 0; i < COUNTRY.length; i++) {
	    		SelectOption op = new SelectOption();
	    		op.setLabel(COUNTRY[i]);
	    		op.setValue(COUNTRY[i]);
	    		countryDatas.add(op);
			}
	    	List<SelectOption> caseCategory = new ArrayList<SelectOption>();
	    	for(int i=1; i<6; i++)
	    	{
	    		SelectOption op = new SelectOption();
	    		op.setLabel(i + "");
	    		op.setValue(i + "");
	    		caseCategory.add(op);
	    	}
	    	request.setAttribute("caseCategory", caseCategory);
	    	request.setAttribute("countryDatas", countryDatas);
	    	
	    	List<SelectOption> relations = new ArrayList<SelectOption>();
	    	for (int i = 0; i < RELATION.length; i++) {
	    		SelectOption op = new SelectOption();
	    		op.setLabel(RELATION[i]);
	    		op.setValue(RELATION[i]);
	    		relations.add(op);
			}
	    	request.setAttribute("relations", relations);
	    	
	    	List<AbuseType> abuseTypes = abuseTypeService.getAllAbuseType();
	    	request.setAttribute("abuseTypes", abuseTypes);
	    	
	    	String typeIdStr = caseInfo.getTypeIds();
			List<String> typeIds = new ArrayList<String>();
			if(typeIdStr != null)
			{
				typeIds = Arrays.asList(typeIdStr.split(","));
			}
			request.setAttribute("typeIds", typeIds);
			
			List<SelectOption> facilityTypes = new ArrayList<SelectOption>();
	    	for (int i = 0; i < FACILITY_TYPE.length; i++) {
	    		SelectOption op = new SelectOption();
	    		op.setLabel(FACILITY_TYPE[i]);
	    		op.setValue(FACILITY_TYPE[i]);
	    		facilityTypes.add(op);
			}
	    	request.setAttribute("facilityTypes", facilityTypes);
	    	
	    	List<Action> actions = actionService.getAllAction();
	    	request.setAttribute("actions", actions);
	    	
	    	List<SelectOption> docTypes = new ArrayList<SelectOption>();
	    	for (int i = 0; i < DOCTYPE.length; i++) {
	    		SelectOption op = new SelectOption();
	    		op.setLabel(DOCTYPE[i]);
	    		op.setValue(DOCTYPE[i]);
	    		docTypes.add(op);
			}
	    	request.setAttribute("docTypes", docTypes);
	    	
	    	List<Drug> drugs = drugService.getAllDrug();
	    	List<SelectOption> datas = new ArrayList<SelectOption>();
	    	for(Drug drug : drugs)
	    	{
	    		SelectOption op = new SelectOption();
	    		op.setGroup(drug.getType());
	    		op.setLabel(drug.getName());
	    		op.setValue(String.valueOf(drug.getId()));
	    		datas.add(op);
	    	}
	    	request.setAttribute("datas", datas);
	    	
	    	List<String> drugIdList = new ArrayList<String>();
	    	String drugIds = caseInfo.getDrugIds();
			if(drugIds != null)
			{
				String[] drugIdArr = drugIds.split(",");
				if(drugIdArr.length > 0)
				{
					drugIdList = Arrays.asList(drugIdArr);
				}
			}
			request.setAttribute("drugIdList", drugIdList);
			
			List<String> actionIdList = new ArrayList<String>();
			String actionIds = caseInfo.getActionIds();
			if(actionIds != null)
			{
				actionIdList = Arrays.asList(actionIds.split(","));
			}
			request.setAttribute("actionIdList", actionIdList);
		}
		return "case/edit";
	}
	
	@RequestMapping(value={"/edit/{id}"}, method = RequestMethod.POST)
	public String editCase(HttpServletRequest request, CaseInfo caseInfo,String[] drugIds,String[] actionsCheckbox,
			String[] abusetypeCheckbox,HttpSession session, @PathVariable Integer id) throws ParseException, NoSuchFieldException, RuntimeException, IllegalArgumentException, IllegalAccessException{
		ChangeHistoryDisplayData displayData = new ChangeHistoryDisplayData();
 
		CaseInfo oldCase = caseInfoService.getCaseInfoById(id);
		CaseInfo  newCase = caseInfoService.getCaseInfoById(id);
		String currUser = (String)request.getSession().getAttribute("userName");
		Date now = new Date();
		
		newCase.setLastUpdateDate(now);
		newCase.setLastUpdatedBy(currUser);
		newCase.setTypeIds(ListUtil.ArrayToString(abusetypeCheckbox, ","));
		newCase.setDrugIds(ListUtil.ArrayToString(drugIds, ","));
		newCase.setActionIds(ListUtil.ArrayToString(actionsCheckbox, ","));
		// 更新界面信息
		newCase.setCaseStart(caseInfo.getCaseStart());
		newCase.setCaseEnd(caseInfo.getCaseEnd());
		newCase.setSummary(caseInfo.getSummary());
		newCase.setOtherAction(caseInfo.getOtherAction());
		newCase.setSequence(caseInfo.getSequence());
		newCase.setDrugsPrescribed(caseInfo.getDrugsPrescribed());
		newCase.setBestTimeToContact(caseInfo.getBestTimeToContact());
		newCase.setBestWayToContact(caseInfo.getBestWayToContact());
		newCase.setDifferentAbusedPerson(caseInfo.getDifferentAbusedPerson());
		newCase.setStillTakeDrugs(caseInfo.getStillTakeDrugs());
		caseInfoService.updateCaseInfo(newCase);
		int caseId = id;
		//先生成caseid
		AbusedPerson oldAbusePerson = abusedPersonService.getAbusedPersonByCaseId(caseId);
		
		abusedPersonService.deleteAbusedPersonByCaseId(caseId);
		AbusedPerson abusedPerson = caseInfo.getAbusedPerson();
		abusedPerson.setCaseId(caseId);
		abusedPersonService.insertAbusedPerson(abusedPerson);
		
		ReportingPerson oldReportingPerson = reportingPersonService.getReportingPersonByCaseId(caseId);
		reportingPersonService.deleteReportingPersonByCaseId(caseId);
		ReportingPerson reportingPerson = caseInfo.getReportedBy();
		reportingPerson.setCaseId(caseId);
		reportingPersonService.insertReportingPerson(reportingPerson);
	 
		int fsize=0; 
		List<FacilityInfo> oldFacilityInfo = FacilityInfoService.getFacilityInfoByCaseId(caseId);
		List<FacilityInfo> newFacilityInfo = new ArrayList<FacilityInfo>();
		
		FacilityInfoService.deleteFacilityInfoByCaseId(caseId);
		if(caseInfo.getFacilityInfos()!=null&&(fsize = caseInfo.getFacilityInfos().size())>0){
			for (int i = 0; i < fsize; i++) {
				FacilityInfo info = caseInfo.getFacilityInfos().get(i);
				info.setCaseId(caseId);
				newFacilityInfo.add(info);
				FacilityInfoService.insertFacilityInfo(info);
			}
		}
		
		int dsize = 0;
		List<DoctorInfo> oldDoctorInfo = doctorInfoService.queryDoctorInfoByCaseId(caseId);
		List<DoctorInfo> newDoctorInfo = new ArrayList<DoctorInfo>();
		
		doctorInfoService.deleteDoctorInfoByCaseId(caseId);
		if(caseInfo.getDoctorInfos()!=null&&(dsize = caseInfo.getDoctorInfos().size())>0){
			for (int i = 0; i < dsize; i++) {
				DoctorInfo info = caseInfo.getDoctorInfos().get(i);
				info.setCaseId(caseId);
				newDoctorInfo.add(info);
				doctorInfoService.insertDoctorInfo(info);
			}
			
		}

		Attorney oldAttorney = attorneyService.getAttorneyByCaseId(caseId);
		attorneyService.deleteAttorneyByCaseId(caseId);
		Attorney newAttorney = caseInfo.getAttorney();
		newAttorney.setCaseId(caseId);
		attorneyService.insertAttorney(newAttorney);
	    
		
		//auditor for abuse case person's info
		// check for caseInfo
		List<String> needComparedFields2 = new ArrayList<String>();

		needComparedFields2.add("caseStart");
		needComparedFields2.add("caseEnd");
		needComparedFields2.add("summary");  
		needComparedFields2.add("typeIds");
		needComparedFields2.add("actionIds");
		needComparedFields2.add("drugIds");
		needComparedFields2.add("otherAction");
		needComparedFields2.add("drugsPrescribed");
		needComparedFields2.add("bestTimeToContact");
		needComparedFields2.add("bestWayToContact");
		needComparedFields2.add("differentAbusedPerson");
		needComparedFields2.add("stillTakeDrugs");
		
		List<ChangeResult> changeResults = DataUtil.compareObjectByFields(oldCase, newCase, needComparedFields2);
		
		if(changeResults.size() > 0)
		{
			CaseAudit audit = new CaseAudit();
			audit.setAction("Update");
			audit.setUpdatedTime(new Date());
			audit.setUpdatedBy(currUser);
			audit.setCaseId(id);
			StringBuilder updateContent = new StringBuilder();
			for(ChangeResult changeResult : changeResults)
			{	
				StringBuilder oldAbuseType = new StringBuilder(); 
				StringBuilder newAbuseType = new StringBuilder();
				StringBuilder oldAction = new StringBuilder(); 
				StringBuilder newAction = new StringBuilder();
				StringBuilder oldDrug = new StringBuilder(); 
				StringBuilder newDrug = new StringBuilder();
				
				switch(changeResult.getKey()){
				case "drugsPrescribed" :
				case "differentAbusedPerson" :
				case "stillTakeDrugs" :
					if (changeResult.getOldValue().toString().equals("1"))
						{
						   flagOld = "yes";
						}else{
						   flagOld = "no";
						}
					if (changeResult.getNewValue().toString().equals("1"))
					{
					   flagNew = "yes";
					}else{
						flagNew = "no";
					}
					
					updateContent.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  
					.append("\"").append(flagOld).append("\"").append(" to ").append("\"").append(flagNew).append("\"")
					.append("<br>");
					flagNew="";
					flagOld="";
					break;
				case "typeIds" :
					
					  if (changeResult.getOldValue().toString().length()>0) {
				      String[] arrayStr =new String[]{};
				      arrayStr = changeResult.getOldValue().toString().split(",");
				      List<String> list = java.util.Arrays.asList(arrayStr);
					
					      for(String s:list){
							  oldAbuseType.append(abuseTypeService.getAbuseTypeName(Integer.parseInt(s))).append(",");
						  }
					  }else{
						  oldAbuseType.append("").append(",");
					  }
					  
					  if (changeResult.getNewValue().toString().length()>0) {
					  String[] arrayStr1 =new String[]{};
				      arrayStr1 = changeResult.getNewValue().toString().split(",");
				      List<String> list2 = java.util.Arrays.asList(arrayStr1);
					  
				      for(String s1:list2){
						  newAbuseType.append(abuseTypeService.getAbuseTypeName(Integer.parseInt(s1))).append(",");
					  }
				      }else{
				    	  newAbuseType.append("").append(",");
				      }
					  oldAbuseType.deleteCharAt(oldAbuseType.length()-1);
					  newAbuseType.deleteCharAt(newAbuseType.length()-1);
					  
					updateContent.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  
					.append("\"").append(oldAbuseType.toString()).append("\"").append(" to ").append("\"").append(newAbuseType.toString()).append("\"")
					.append("<br>");
					break;
				case "actionIds":
					if (changeResult.getOldValue().toString().length()>0){
						 String[] arrayStr3 =new String[]{};
					      arrayStr3 = changeResult.getOldValue().toString().split(",");
					      List<String> list3 = java.util.Arrays.asList(arrayStr3);
						
						      for(String s3:list3){
								  oldAction.append(actionService.getActionById(Integer.parseInt(s3)).getName()).append(",");
							  }
						}else{
							  oldAction.append("").append(",");
						  }
						  
					if (changeResult.getNewValue().toString().length()>0){
						 String[] arrayStr4 =new String[]{};
					      arrayStr4 = changeResult.getNewValue().toString().split(",");
					      List<String> list4 = java.util.Arrays.asList(arrayStr4);
						
						      for(String s4:list4){
						    	  newAction.append(actionService.getActionById(Integer.parseInt(s4)).getName()).append(",");
							  }
						}else{
							  newAction.append("").append(",");
						  }
					oldAction.deleteCharAt(oldAction.length()-1);
					newAction.deleteCharAt(newAction.length()-1);
					updateContent.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  
					.append("\"").append(oldAction.toString()).append("\"").append(" to ").append("\"").append(newAction.toString()).append("\"")
					.append("<br>");
					break;
				case "otherAction":
					updateContent.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  
					.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
					.append("<br>");
					
				break;
				case "drugIds":
					if (changeResult.getOldValue().toString().length()>0){
						 String[] arrayStr5 =new String[]{};
					      arrayStr5 = changeResult.getOldValue().toString().split(",");
					      List<String> list5 = java.util.Arrays.asList(arrayStr5);
						
						      for(String s5:list5){
								  oldDrug.append(drugService.getDrugById(Integer.parseInt(s5)).getName()).append(",");
							  }
						}else{
							  oldDrug.append("").append(",");
						  }
						  
					if (changeResult.getNewValue().toString().length()>0){
						 String[] arrayStr6 =new String[]{};
					      arrayStr6 = changeResult.getNewValue().toString().split(",");
					      List<String> list6 = java.util.Arrays.asList(arrayStr6);
						
						      for(String s6:list6){
						    	  newDrug.append(drugService.getDrugById(Integer.parseInt(s6)).getName()).append(",");
							  }
						}else{
							  newDrug.append("").append(",");
						  }
					oldDrug.deleteCharAt(oldDrug.length()-1);
					newDrug.deleteCharAt(newDrug.length()-1);
					updateContent.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  
					.append("\"").append(oldDrug.toString()).append("\"").append(" to ").append("\"").append(newDrug.toString()).append("\"")
					.append("<br>");
					break;
					
				default: 
					
					updateContent.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  
					.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
					.append("<br>");

				}
				
			}
			audit.setUpdatedAfter(updateContent.toString());
			caseAuditService.insertCaseAudit(audit);
			}
		
		//auditor for abused person
				List<String> needComparedFields3 = new ArrayList<String>();

				needComparedFields3.add("firstName");
				needComparedFields3.add("middleName");
				needComparedFields3.add("lastName");  
				needComparedFields3.add("email");
				needComparedFields3.add("city");
				needComparedFields3.add("state");
				needComparedFields3.add("country");
				needComparedFields3.add("telephone");
				needComparedFields3.add("zip");
				needComparedFields3.add("birthDay");
				needComparedFields3.add("streetAddress");
				needComparedFields3.add("age");
				
				List<ChangeResult> changeResults3 = DataUtil.compareObjectByFields(oldAbusePerson, abusedPerson, needComparedFields3);
				
				if(changeResults3.size() > 0)
				{
					CaseAudit audit2 = new CaseAudit();
					audit2.setAction("Update");
					audit2.setUpdatedTime(new Date());
					audit2.setUpdatedBy(currUser);
					audit2.setCaseId(id);
					StringBuilder updateContent2 = new StringBuilder();
					for(ChangeResult changeResult : changeResults3)
					{	
						
							updateContent2.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledNameForAbusedPerson(changeResult.getKey())).append("\"").append(" has changed from ")  
							.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
							.append("<br>");

						
					}
					audit2.setUpdatedAfter(updateContent2.toString());
					caseAuditService.insertCaseAudit(audit2);
					}
				
				//auditor for reporting person
				List<String> needComparedFields4 = new ArrayList<String>();

				needComparedFields4.add("firstName");
				needComparedFields4.add("middleName");
				needComparedFields4.add("lastName");  
				needComparedFields4.add("email");
				needComparedFields4.add("city");
				needComparedFields4.add("state");
				needComparedFields4.add("country");
				needComparedFields4.add("telephone");
				needComparedFields4.add("zip");
				needComparedFields4.add("birthDay");
				needComparedFields4.add("streetAddress");
				needComparedFields4.add("relation");  
				needComparedFields4.add("relationOther"); 	
				
				List<ChangeResult> changeResults4 = DataUtil.compareObjectByFields(oldReportingPerson, reportingPerson, needComparedFields4);
				
				if(changeResults4.size() > 0)
				{
					CaseAudit audit3 = new CaseAudit();
					audit3.setAction("Update");
					audit3.setUpdatedTime(new Date());
					audit3.setUpdatedBy(currUser);
					audit3.setCaseId(id);
					StringBuilder updateContent3 = new StringBuilder();
					for(ChangeResult changeResult : changeResults4)
					{	
							updateContent3.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledNameForReportingPerson(changeResult.getKey())).append("\"").append(" has changed from ")  
							.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
							.append("<br>");
					}
					audit3.setUpdatedAfter(updateContent3.toString());
					caseAuditService.insertCaseAudit(audit3);
					}
				
				//auditor for facility info
				List<String> needComparedFields5 = new ArrayList<String>();
    
				needComparedFields5.add("name");
				needComparedFields5.add("city");
				needComparedFields5.add("state");  
				needComparedFields5.add("zip");
				needComparedFields5.add("country");
				needComparedFields5.add("streetAddress");
				needComparedFields5.add("telephone");
				needComparedFields5.add("type");
				needComparedFields5.add("typeOther");
				CaseAudit audit4 = new CaseAudit();
				StringBuilder updateContent4 = new StringBuilder();
				for (int i=0;i<oldFacilityInfo.size();i++){
					List<ChangeResult> changeResults5 = DataUtil.compareObjectByFields(oldFacilityInfo.get(i), newFacilityInfo.get(i), needComparedFields5);
					
					if(changeResults5.size() > 0)
					{
					
						audit4.setAction("Update");
						audit4.setUpdatedTime(new Date());
						audit4.setUpdatedBy(currUser);
						audit4.setCaseId(id);
					
						for(ChangeResult changeResult : changeResults5)
						{	
								updateContent4.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledNameForFacility(changeResult.getKey())).append("\"").append(" has changed from ")  
								.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
								.append("<br>");
						}
					}
				}
				if(null != updateContent4 && updateContent4.toString().length()>1){
					audit4.setUpdatedAfter(updateContent4.toString());
					caseAuditService.insertCaseAudit(audit4);
				}

				
				//auditor for doctor info
				List<String> needComparedFields6 = new ArrayList<String>();
    			
				needComparedFields6.add("name");
				needComparedFields6.add("lastName");
				needComparedFields6.add("docType");  
				needComparedFields6.add("zip");
				needComparedFields6.add("city");
				needComparedFields6.add("state");
				needComparedFields6.add("country");
				needComparedFields6.add("streetAddress");
				needComparedFields6.add("telephone");
				StringBuilder updateContent5 = new StringBuilder();
				CaseAudit audit5 = new CaseAudit();
				for (int i=0;i<oldDoctorInfo.size();i++){
					List<ChangeResult> changeResults6 = DataUtil.compareObjectByFields(oldDoctorInfo.get(i), newDoctorInfo.get(i), needComparedFields6);
					
					if(changeResults6.size() > 0)
					{
						
						audit5.setAction("Update");
						audit5.setUpdatedTime(new Date());
						audit5.setUpdatedBy(currUser);
						audit5.setCaseId(id);
						
						for(ChangeResult changeResult : changeResults6)
						{	
								updateContent5.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledNameForDoctor(changeResult.getKey())).append("\"").append(" has changed from ")  
								.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
								.append("<br>");
						}
						}
				}
				if(null != updateContent5 && updateContent5.toString().length()>1){
				audit5.setUpdatedAfter(updateContent5.toString());
				caseAuditService.insertCaseAudit(audit5);
				}
					
					//auditor for attorney info
					List<String> needComparedFields7 = new ArrayList<String>();
				  
					needComparedFields7.add("name");
					needComparedFields7.add("city");
					needComparedFields7.add("state");
					needComparedFields7.add("country");
					needComparedFields7.add("telephone");
					needComparedFields7.add("zip");
					needComparedFields7.add("streetAddress");
					needComparedFields7.add("workWithAttorney");
					needComparedFields7.add("assistanceAttorney");  
					needComparedFields7.add("status");
					
					List<ChangeResult> changeResults7 = DataUtil.compareObjectByFields(oldAttorney, newAttorney, needComparedFields7);
					
					if(changeResults7.size() > 0)
					{
						CaseAudit audit7 = new CaseAudit();
						audit7.setAction("Update");
						audit7.setUpdatedTime(new Date());
						audit7.setUpdatedBy(currUser);
						audit7.setCaseId(id);
						StringBuilder updateContent7 = new StringBuilder();
						for(ChangeResult changeResult : changeResults7)
						{	
								
							switch(changeResult.getKey()){
							case "workWithAttorney" :
							case "assistanceAttorney":
								if ((changeResult.getOldValue()!=null)&&("1".equals(changeResult.getOldValue().toString())))
									{
									   flagOld = "yes";
									}else{
									   flagOld = "no";
									}
								if((changeResult.getNewValue()!=null)&&("1".equals(changeResult.getNewValue().toString())))
								{
								   flagNew = "yes";
								}else{
									flagNew = "no";
								}
								
							    updateContent7.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledNameForAttorney(changeResult.getKey())).append("\"").append(" has changed from ")  
								.append("\"").append(flagOld).append("\"").append(" to ").append("\"").append(flagNew).append("\"")
								.append("<br>");
								flagNew="";
								flagOld="";
								break;
								default:
							      updateContent7.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledNameForAttorney(changeResult.getKey())).append("\"").append(" has changed from ")  
								.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
								.append("<br>");
							}
						}
						audit7.setUpdatedAfter(updateContent7.toString());
						caseAuditService.insertCaseAudit(audit7);
					}

		return "redirect:/case/edit/" + caseInfo.getId();
	}
	
	@ResponseBody
	@RequestMapping(value={"/recall/{id}"}, method = RequestMethod.POST)
	public AjaxResult recall(HttpServletRequest request, @PathVariable Integer id)
	{
		caseInfoService.updateCaseStatus(id, CaseStatus.INPROCESS.getValue(), request.getSession().getAttribute("userName").toString());
		return AjaxResult.SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping(value={"/complete/{id}"}, method = RequestMethod.POST)
	public AjaxResult complete(HttpServletRequest request, @PathVariable Integer id)
	{
		caseInfoService.updateCaseStatus(id, CaseStatus.COMPLETED.getValue(), request.getSession().getAttribute("userName").toString());
		return AjaxResult.SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping(value={"/invalid/{id}"}, method = RequestMethod.POST)
	public AjaxResult invalid(HttpServletRequest request, @PathVariable Integer id)
	{
		caseInfoService.updateCaseStatus(id, CaseStatus.INVALID.getValue(), request.getSession().getAttribute("userName").toString());
		return AjaxResult.SUCCESS;
	}
	
}
